﻿using System.Globalization;
using System.Linq;
using Styx.Common;
using System;
using System.Net;
using System.Text;
using System.IO;
using Styx;

namespace HBTracker
{
    public class Util
    {

        public static string SendNotification(string deviceId, string message)
        {
            const string googleAppID = "AIzaSyCx6FACQbbOxXNKjTC2m6TePcrh_AwD2Hg";
            const string senderID = "320209084966";
            var value = message;
            if (HBTrackerSettings.Instance.Debug) Logging.Write("[HBTracker] toAndroid start ");

            try
            {
                WebRequest tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
                tRequest.Method = "post";
                tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
                tRequest.Headers.Add(string.Format("Authorization: key={0}", googleAppID));

                tRequest.Headers.Add(string.Format("Sender: id={0}", senderID));

                var postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + DateTime.Now.ToString(CultureInfo.InvariantCulture) + "&registration_id=" + deviceId + "";
                Console.WriteLine(postData);
                var byteArray = Encoding.UTF8.GetBytes(postData);
                tRequest.ContentLength = byteArray.Length;

                var dataStream = tRequest.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                var tResponse = tRequest.GetResponse();

                dataStream = tResponse.GetResponseStream();

                if (dataStream != null)
                {
                    var tReader = new StreamReader(dataStream);

                    var sResponseFromServer = tReader.ReadToEnd();

                    tReader.Close();
                    dataStream.Close();
                    tResponse.Close();
                    if (HBTrackerSettings.Instance.Debug) Logging.Write("[HBTracker] toAndroid {0} ", sResponseFromServer);
                    return sResponseFromServer;
                }
            }
            catch (WebException e)
            {
                var responseStream = e.Response.GetResponseStream();

                if (responseStream != null)
                {
                    var responseReader = new StreamReader(responseStream);

                    var responseString = responseReader.ReadToEnd();
                    Logging.Write("[HBTracker] Fehler: {0}", responseString);
                }
            }
            catch (Exception e)
            {
                Logging.Write("[HBTracker] Fehler: {0}", e.Message);
            }
            return "";
        }

        public static void Log(string message)
        {
            if (HBTrackerSettings.Instance.Debug)
                using (StreamWriter w = File.AppendText("log.txt"))
                {
                    Logging.Write("[HBTracker] Fehler: {0}", StyxWoW.Me.IsOutOfBounds);
                    w.Write("\r\nLog Entry : ");
                    w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                        DateTime.Now.ToLongDateString());
                    w.WriteLine("  :");
                    w.WriteLine("  : {0}", message);
                    w.WriteLine("Name  : {0}", StyxWoW.Me.Name);
                    w.WriteLine("isGhost  : {0}", StyxWoW.Me.IsGhost);
                    w.WriteLine("isOutof  : {0}", StyxWoW.Me.IsOutOfBounds);

                    w.WriteLine("-------------------------------");
                }
        }

        public static Boolean SendToProwl(string header, string message)
        {
            if (HBTrackerSettings.Instance.ProwlApi == "")
                return false;

            string[] sendParam = {"apikey", "application", "event", "description", "priority"};
            string[] sendVal = {HBTrackerSettings.Instance.ProwlApi, "HBTracker", header, message, "1"};
            string response = HttpPost("https://api.prowlapp.com/publicapi/add", sendParam, sendVal);
            return response.Contains("success");
        }

        public static string PostToFtp(string imagFilePath)
        {
            try
            {
                FileStream fileStream = File.OpenRead(imagFilePath);
                var imageData = new byte[fileStream.Length];
                fileStream.Read(imageData, 0, imageData.Length);
                fileStream.Close();


                const int maxUriLength = 32766;
                string base64Img = Convert.ToBase64String(imageData);
                var sb = new StringBuilder();

                for (int i = 0; i < base64Img.Length; i += maxUriLength)
                {
                    sb.Append(Uri.EscapeDataString(base64Img.Substring(i, Math.Min(maxUriLength, base64Img.Length - i))));
                }

                string uploadRequestString = "image=" + sb;
                string url = HBTrackerSettings.Instance.ScriptUrl;
                if (!url.StartsWith("http://")) url = "http://" + url;

                var webRequest = (HttpWebRequest)WebRequest.Create(url);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ServicePoint.Expect100Continue = false;

                var streamWriter = new StreamWriter(webRequest.GetRequestStream());
                streamWriter.Write(uploadRequestString);
                streamWriter.Close();

                WebResponse response = webRequest.GetResponse();
                Stream responseStream = response.GetResponseStream();
                if (responseStream != null)
                {
                    var responseReader = new StreamReader(responseStream);
                    var responseString = responseReader.ReadToEnd();

                    return responseString;
                }
            }
            catch (WebException e)
            {
                var responseStream = e.Response.GetResponseStream();
                if (responseStream != null)
                {
                    var responseReader = new StreamReader(responseStream);
                    var responseString = responseReader.ReadToEnd();
                    Logging.Write("[HBTracker] Erreur (Web) -> {0}", responseString);
                }
            }
            catch (Exception e)
            {
                Logging.Write("[HBTracker] Erreur (Exception) -> {0}", e.Message);
            }
            return "";
        }

        public static string HttpPost(string url, string[] paramName, string[] paramVal)
        {
            try
            {
                var req = WebRequest.Create(new Uri(url))
                                     as HttpWebRequest;
                if (req != null)
                {
                    req.Method = "POST";
                    req.ContentType = "application/x-www-form-urlencoded";
                }

                var paramz = new StringBuilder();
                for (int i = 0; i < paramName.Length; i++)
                {
                    paramz.Append(paramName[i]);
                    paramz.Append("=");
                    paramz.Append(WebUtility.HtmlDecode(paramVal[i]));
                    paramz.Append("&");
                }

                // Encode the parameters as form data:
                var formData =
                    Encoding.UTF8.GetBytes(paramz.ToString());

                if (req != null)
                {
                    req.ContentLength = formData.Length;

                    // Send the request:
                    using (var post = req.GetRequestStream())
                    {
                        post.Write(formData, 0, formData.Length);
                    }

                    // Pick up the response:
                    string result = null;
                    using (var resp = req.GetResponse() as HttpWebResponse)
                    {
                        if (resp != null)
                        {
                            // ReSharper disable AssignNullToNotNullAttribute
                            var reader = new StreamReader(resp.GetResponseStream());
                            // ReSharper restore AssignNullToNotNullAttribute
                            result = reader.ReadToEnd();
                        }
                    }

                    return result;
                }
            }
            catch (WebException e)
            {
                var responseStream = e.Response.GetResponseStream();

                if (responseStream != null)
                {
                    var responseReader = new StreamReader(responseStream);
                    var responseString = responseReader.ReadToEnd();
                    if (HBTrackerSettings.Instance.Debug) Logging.Write("[HBTracker] Fehler: {0}", responseString);
                }
                return "";
            }

            catch (Exception e)
            {
                Logging.Write("[HBTracker] Fehler: {0}", e.Message);
                return "";
            }
            return null;
        }

        public static FileInfo GetLatestWritenFileFileInDirectory(DirectoryInfo directoryInfo)
        {
            if (directoryInfo == null || !directoryInfo.Exists)
                return null;

            var files = directoryInfo.GetFiles();
            DateTime[] lastWrite = {DateTime.MinValue};
            FileInfo lastWritenFile = null;

            foreach (var file in files.Where( f => f.LastWriteTime > lastWrite[0]))
		    {
		            lastWrite[0] = file.LastWriteTime;
		            lastWritenFile = file;
		    }
		    return lastWritenFile;
        }
    }
}